package flex.cc.medical.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;

import flex.cc.PublicUtil;
import flex.cc.core.support.BaseController;
import flex.cc.medical.dto.entity.ImportCardEntity;
import flex.cc.medical.service.ImportCardService;
import flex.cc.medical.service.impl.ExportCardService;
import flex.cc.order.manage.service.DownLoadService;
import flex.cc.util.FileDownloadUtil;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 * @author WANGCONG
 * 2022年2月7日上午10:35:16
 * @desc 医护类卡券序列码控制层
 */
@RestController
@RequestMapping(value = "/medical")
public class ImportCardController extends BaseController{

	@Resource
	private ImportCardService importCardService;
	@Resource
	private ExportCardService exportCardService;
	@Resource
    private DownLoadService downLoadService;

	/**
	 * 
	 * @author WANGCONG
	 * 2022年2月7日上午10:38:52
	 * @desc 医护类卡券模板下载
	 */
	@PostMapping(value = "/exportTemplate")
    @ApiOperation(httpMethod = "POST", value = "卡券模板下载")
	public void exportTemplate(HttpServletRequest request, HttpServletResponse response){
		logger.info("医护类卡券导入模板下载");
		String fileParentPath = System.getProperty("user.dir") + File.separator + "package" + File.separator + System.currentTimeMillis();
		String fileName = "医护类卡券模板";
		exportCardService.downLoadTemplate(request, response, fileParentPath, fileName);
		String filepath = fileParentPath + File.separator + fileName + ".xlsx";
        FileDownloadUtil.downloadByFilepath(request, response, filepath);
	}
	
	/**
	 * 
	 * @author WANGCONG
	 * 2022年2月8日上午10:12:51
	 * @desc 医护类卡券导入test
	 */
	@PostMapping("/upFile_v1")
	public Wrapper<String> upLoadFile(@RequestParam("file") MultipartFile file,HttpServletResponse response,HttpServletRequest request){
		logger.info("医护类卡券导入");
		String contentType = file.getContentType();      //文件类型
		String fileName =	file.getOriginalFilename();	 //文件名字
		System.out.println("文件类型="+contentType+",文件名称="+fileName);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("status", "success");
		return WrapMapper.ok(JSON.toJSONString(result));
	}
	
	@SuppressWarnings({ "deprecation", "static-access" })
	public static String getValue(XSSFCell xssfRow) {
    	if(xssfRow==null){
    		return "";
    	}
		String value="";
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
        	value = String.valueOf(xssfRow.getBooleanCellValue()).trim();
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            value = String.valueOf(xssfRow.getNumericCellValue()).trim();
        } else {
        	value = String.valueOf(xssfRow.getStringCellValue()).trim();
        }
        return value;
    }
	
	/**
	 * 
	 * @author WANGCONG
	 * 2022年2月9日上午10:02:36
	 * @desc 医护类卡券导入
	 */
	@SuppressWarnings("resource")
	@PostMapping(value = "/upFile")
    @ResponseBody
    public Wrapper<String> upFile(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("status", "success");
        result.put("data", "yaoxi");
		InputStream in = excelFile.getInputStream();
		try {
			OPCPackage opcPackage = OPCPackage.open(in);
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(opcPackage);
			XSSFSheet sheet = xssfWorkbook.getSheetAt(0);//工作表对象
            int rowLength = sheet.getLastRowNum();//data数据总行数（抛去标题头）
            Row row = sheet.getRow(0);//工作表的列
            int colLength = row.getLastCellNum();//总列数
            if(colLength!=5){
            	result.put("status", "error1");
        		result.put("msg", "导入文件列数与模板要求不符");
        		return WrapMapper.ok(JSON.toJSONString(result));
            }
            if(rowLength>500){
            	result.put("status", "error1");
        		result.put("msg", "导入文件行数不得超过500条");
        		return WrapMapper.ok(JSON.toJSONString(result));
            }
            List<ImportCardEntity> cardList = new ArrayList<>();
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            	XSSFRow xssfRow = sheet.getRow(rowNum);
            	if (xssfRow != null) {
            		XSSFCell r1 = xssfRow.getCell(0);
                    XSSFCell r2 = xssfRow.getCell(1);
                    XSSFCell r3 = xssfRow.getCell(2);
                    XSSFCell r4 = xssfRow.getCell(3);
                    XSSFCell r5 = xssfRow.getCell(4);
                    String activityId = getValue(r1);   //类型编码
                    String activityName = getValue(r2); //类型名称
                    String serviceName = getValue(r3);  //服务商名称
                    String cardNum = getValue(r4);      //卡券序列码
                    String activateCode = getValue(r5); //激活兑换码
                    ImportCardEntity card = new ImportCardEntity();
                    card.setActivityId(activityId);
                    card.setActivityName(activityName);
                    card.setServiceName(serviceName);
                    card.setCardNum(cardNum);
                    card.setActivateCode(activateCode);
                    cardList.add(card);
            	}
            }
            if(cardList.size()>0){
            	List<ImportCardEntity> errorList = new ArrayList<>();
            	List<String> cardNumList = new ArrayList<>(); //当前excel中已判断过的卡券码
            	List<String> activateCodeList = new ArrayList<>();//当前excel中已判断过的激活码
            	for(int i=0; i<cardList.size(); i++){
    				ImportCardEntity currentCard = cardList.get(i);
    				String activityId = currentCard.getActivityId();
    				String activityName = currentCard.getActivityName();
    				String serviceName = currentCard.getServiceName();
    				String cardNum = currentCard.getCardNum();
    				String activateCode = currentCard.getActivateCode();
    				if(PublicUtil.isEmpty(activityId) || PublicUtil.isEmpty(activityName) || PublicUtil.isEmpty(serviceName)
    						|| PublicUtil.isEmpty(cardNum) || PublicUtil.isEmpty(activateCode)){
    					currentCard.setRemark("有空值，请补充完整");
    					errorList.add(currentCard);
    					continue;
    				}
    				//Excel中去重cardNum和activateCode
    				if(cardNumList.contains(cardNum)){
    					currentCard.setRemark("卡券码已存在");
    					errorList.add(currentCard);
    					continue;
    				}
    				if(activateCodeList.contains(activateCode)){
    					currentCard.setRemark("激活码已存在");
    					errorList.add(currentCard);
    					continue;
    				}
    				Map<String, Object> params = new HashMap<String, Object>();
    				params.put("cardNum", cardNum);
    				params.put("activateCode", activateCode);
					//DB中去重cardNum和activateCode
    				ImportCardEntity vo = importCardService.getOneByParams(params);
    				if(vo!=null){
    					String db_cardNum = vo.getCardNum();
    					String db_activateCode = vo.getActivateCode();
    					String remark = "";
    					if(cardNum.equals(db_cardNum) && activateCode.equals(db_activateCode)){
    						cardNumList.add(cardNum);
    						activateCodeList.add(activateCode);
    						remark = "卡券码和激活码已存在";
    					}else if(cardNum.equals(db_cardNum)){
    						cardNumList.add(cardNum);
    						remark = "卡券码已存在";
    					}else{
    						activateCodeList.add(activateCode);
    						remark = "激活码已存在";
    					}
    					currentCard.setRemark(remark);
    					errorList.add(currentCard);
    					continue;
    				}else{
    					//保存入库
    					Date time = new Date();
    					currentCard.setCreateTime(time);
    					currentCard.setUpdateTime(time);
    					currentCard.setStatus("0");
    					importCardService.insertVo(currentCard);
    					cardNumList.add(cardNum);
    					activateCodeList.add(activateCode);
    				}
    			}
            	if(errorList.size()>0){
            		result.put("status", "error2");
            		result.put("data", errorList);
            	}
            }
		} catch (InvalidFormatException e) {
			result.put("status", "error");
			result.put("data", "yaoxi2");
		}
		
        return WrapMapper.ok(JSON.toJSONString(result));
        //return WrapMapper.error();
    }

	/**
	 * 
	 * @author WANGCONG
	 * 2022年2月10日上午9:52:18
	 * @desc 医护类卡券导出错误数据
	 */
	@PostMapping(value = "/exportErrorData")
    @ApiOperation(httpMethod = "POST", value = "卡券错误信息下载")
	public void exportErrorData(@RequestBody List<ImportCardEntity> errorData, HttpServletRequest request, HttpServletResponse response){
		logger.info("卡券错误信息下载");
		String fileParentPath = System.getProperty("user.dir") + File.separator + "order" + File.separator + System.currentTimeMillis();
        String fileName = "卡券错误数据";
        downLoadService.downLoadMedicalCard(request, response, errorData, fileParentPath, fileName);
        String filepath = fileParentPath + File.separator + fileName + ".xlsx";
        FileDownloadUtil.downloadByFilepath(request, response, filepath);
	}
	
	/**
	*
	* @author WANGCONG
	* 2022年2月10日上午10:42:06
	* @desc 分页查询导入卡券信息
	*/
	@PostMapping(value = "/cardListWithPage")
    @ApiOperation(httpMethod = "POST", value = "查询导入卡券列表")
    public Wrapper<IPage<ImportCardEntity>> queryOrderListWithPage(@ApiParam(name = "cardMain", value = "导入卡券信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("查询导入卡券列表cardMain={}", reqVo);
        ImportCardEntity cardDto = new ImportCardEntity();
        cardDto.setPageNum(Integer.parseInt(reqVo.get("pageNum").toString()));
        cardDto.setPageSize(Integer.parseInt(reqVo.get("pageSize").toString()));
        IPage<ImportCardEntity> page = importCardService.queryListWithPage(cardDto);
        return WrapMapper.ok(page);
    }
	
}
